<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="客服姓名">
          <el-input
            v-model="formInline.user_name"
            placeholder="请输入客服姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="客服电话">
          <el-input
            v-model="formInline.telephone"
            placeholder="请输入客服手机号"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item label="客服账号">
          <el-input
            v-model="formInline.seller_name"
            placeholder="请输入客服账号"
          ></el-input>
        </el-form-item> -->
        <el-form-item>
          <div class="gauge">
            <el-button type="primary" @click="onSubmit">查询</el-button>
            <div class="gauge">
              <el-button type="primary" @click="onReset">重置</el-button>
            </div>
            <el-button type="primary" @click="onNewly">新增客服</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <!-- 客服列表 -->
    <div class="text item">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
      >
        <el-table-column align="center" label="ID" width="70" prop="id">
        </el-table-column>
        <el-table-column prop="user_name" align="center" label="客服姓名">
        </el-table-column>
        <el-table-column prop="avatar" align="center" label="头像">
          <template slot-scope="scope">
            <el-image
              style="width: 60px; height: 60px"
              :src="imgHeader + scope.row.avatar"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="telephone" align="center" label="手机号">
        </el-table-column>
        <!-- <el-table-column prop="job_number" align="center" label="工号">
        </el-table-column> -->
        <!-- <el-table-column prop="seller_name" align="center" label="账号">
        </el-table-column> -->
        <el-table-column prop="password" align="center" label="密码">
        </el-table-column>
        <!-- <el-table-column prop="type" align="center" label="分类">
        </el-table-column> -->
        <el-table-column prop="create_time" align="center" label="创建时间">
        </el-table-column>
        <el-table-column prop="status" align="center" label="状态">
          <template slot-scope="scope">
            <!-- 0是启用，1是禁用 -->
            <span>{{ scope.row.status == 1 ? "启用" : "停用" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              v-if="scope.row.status == 0"
              size="mini"
              type="success"
              @click="handleStatus(scope.row)"
              >启用</el-button
            >
            <el-button
              v-if="scope.row.status == 1"
              size="mini"
              type="warning"
              @click="handleStatus(scope.row)"
              >停用</el-button
            >
            <el-button
              v-if="scope.row.status == 0"
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-sizes="[10, 20, 30, 40, 50, 60]"
      :page-size="10"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
    <!-- 新增客服弹出层 -->
    <el-dialog
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <el-form ref="form" :rules="rules" :model="form" label-width="80px">
        <div class="formUser">
          <el-form-item label="姓名" prop="user_name">
            <el-input v-model="form.user_name"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="telephone">
            <el-input v-model="form.telephone"></el-input>
          </el-form-item>
          <!-- <el-form-item label="账号" prop="seller_name">
            <el-input
              v-model="form.seller_name"
              @blur="psiResultNamePre"
            ></el-input>
          </el-form-item> -->
          <div v-if="requirePassWord == '是'">
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password"></el-input
            ></el-form-item>
          </div>
          <div v-if="requirePassWord == '否'" prop="pwd">
            <el-form-item label="密码">
              <el-input v-model="form.password"></el-input>
            </el-form-item>
          </div>
          <!-- <el-form-item label="员工工号" prop="job_number">
            <el-input v-model="form.job_number"></el-input>
          </el-form-item> -->
          <el-form-item label="角色" prop="role_id">
            <el-select v-model="form.role_id" placeholder="请选择">
              <el-option
                v-for="item in options1"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="菜单权限" prop="limits_id">
            <el-cascader
              v-model="form.limits_id"
              :options="options1"
              :props="{
                multiple: true,
                value: 'id',
                label: 'name',
                children: 'son',
                checkStrictly: true,
              }"
            ></el-cascader>
          </el-form-item> -->
          <el-form-item label="头像" prop="imageUrl1">
            <div class="unlodBox">
              <el-upload
                class="upload-demo"
                action
                :http-request="uploadFiles"
                ref="upload"
                :limit="fileLimit"
                :on-remove="handleRemove"
                :file-list="fileList"
                :on-exceed="handleExceed"
                :before-upload="beforeUpload"
                :show-file-list="false"
                :headers="headers"
                :on-change="fileChange"
              >
                <el-image
                  v-if="imageUrl"
                  class="imageGood"
                  :src="imageUrl"
                  style="width: 360px; height: 180px"
                ></el-image>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过5M
                </div>
              </el-upload>
            </div>
          </el-form-item>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import { uploadFiles } from "../../../../utils/api";
import { compressImage } from "../../../../assets/js/compressImage";
import {
  getHardwareKeFe,
  getHardwareKeFeStatus,
  editHardwareKeFe,
  getMainKeFuSelect,
  delHardwareKeFe,
  getPrefix,
} from "../../../../utils/main";
export default {
  data() {
    return {
      //弹窗
      dialogVisible: false,
      loading: false,
      token: sessionStorage.getItem("token"),
      seller_id: sessionStorage.getItem("seller_id"),
      // seller_id: 8,
      formInline: {
        user_name: "",
        telephone: "",
        seller_name: "",
      },
      aeccount: "",
      options1: [],
      tableData: [
        // {
        //   index: "20-02",
        //   name: "张三",
        //   avatar: "上海市普陀区金沙江路 1518 弄",
        //   tel: "16738926942",
        //   jobNumber: "1902983",
        //   number: "12372838238",
        //   msg: "jo123456",
        //   classify: "水站",
        //   createTime: "2021年10月10日",
        //   state: "启用",
        //   operate: "编辑",
        // },
      ],
      // 启用停用按钮颜色
      states: "启用",
      // 删除按钮是否可见
      value: false,
      // 启用停用按钮颜色
      btncolor: "success",
      //新增
      form: {
        user_name: "",
        telephone: "",
        seller_name: "",
        password: "",
        avatar: "111",
        seller_id: "111",
        type: "",
        job_number: "",
        role_id: "1",
      },
      seller_names: "",
      //分页器
      total: 0,
      limit: 10,
      page: 1,
      is_shop: 0,
      currentPage: 1,
      //上传图片
      imageUrl: "",
      imageUrl1: "",
      requirePassWord: "",
      fileList: [],
      fileType: ["png", "jpg", "jpeg"],
      fileLimit: 1,
      headers: { "Content-Type": "multipart/form-data" },
      srcList2: {},
      imgHeader: this.Global.imgHeader,
      //校验
      rules: {
        user_name: [
          { required: true, message: "请输入客服姓名", trigger: "blur" },
        ],
        telephone: [
          { required: true, message: "请输入客服手机号", trigger: "blur" },
          {
            validator: function (rule, value, callback) {
              if (/^1[3456789]\d{9}$/.test(value) == false) {
                callback(new Error("手机号格式错误"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        job_number: [
          { required: true, message: "请输入员工工号", trigger: "blur" },
        ],
        seller_name: [
          { required: true, message: "请输入账号", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        role_id: [
          { required: true, message: "请选择菜单权限", trigger: "change" },
        ],
        // imageUrl1: [{ required: true, message: "请上传头像", trigger: "blur" }],
      },
    };
  },
  methods: {
    clearData() {
      this.form = {
        user_name: "",
        telephone: "",
        seller_name: "",
        password: "",
        avatar: "",
        seller_id: "",
        cus_type: "",
        role_id: "",
      };
      this.imageUrl = "";
      this.imageUrl1 = "";
    },
    // 新增账号添加固定前缀
    // psiResultNamePre(e) {
    //   console.log("111", this.form.seller_name);
    //   if (!this.form.seller_name.startsWith(this.fixIdentStr)) {
    //     this.form.seller_name = this.fixIdentStr + this.form.seller_name;
    //     console.log("222", this.form.seller_name);
    //   }
    // },
    // async getPrefixIdentIfication() {
    //   let res = await getPrefix(this.token, this.seller_id);
    //   if (res.data.status) {
    //     this.fixIdentStr = res.data.data;
    //   } else {
    //     if (res.data.msg == "token失效,请重新进行登录") {
    //       this.$router.push("/materilsLogin");
    //     }
    //     if (res.data.msg == "此账号没有权限") {
    //       this.$message.error(res.data.msg);
    //       this.loading = false;
    //     }
    //     let timer = setTimeout(() => {
    //       this.$message.error(res.data.msg);
    //     }, 5000);
    //   }
    // },
    async getSelect() {
      // this.loading = true;
      let res = await getMainKeFuSelect(this.token, this.seller_id)
        .then((res) => {
          // console.log(this.type, 88888);
          if (res.data.status) {
            this.options1 = res.data.data;
            // this.total = res.data.data.count;
            // console.log(111, this.options);
            // let timer = setTimeout(() => {
            //   this.loading = false;
            //   clearTimeout(timer);
            // }, 400);
          } else {
            if (res.data.msg == "token失效,请重新进行登录") {
              this.$router.push("/materilsLogin");
            }
            if (res.data.msg == "此账号没有权限") {
              this.$message.error(res.data.msg);
              this.loading = false;
            }
            // let timer = setTimeout(() => {
            //   this.$message.error(res.data.msg);
            // }, 5000);
          }
        })
        .catch((err) => {
          console.log(err.message);
        });
    },
    //查询
    onSubmit() {
      // console.log("查询!");
      this.page = 1;
      // if (this.formInline.seller_name === "0") {
      //   this.seller_names = "-1";
      // } else {
      //   this.seller_names = this.formInline.seller_name;
      // }
      this.getList();
    },
    //重置
    onReset() {
      this.formInline = {
        user_name: "",
        telephone: "",
        seller_name: "",
      };
      // this.seller_names = "";
      this.getList();
    },
    //新增客服
    onNewly() {
      this.clearData();
      this.requirePassWord = "是";
      this.imageUrl = "";
      this.imageUrl1 = "";
      this.dialogVisible = true;
    },
    // 序号排序
    indexMethod(index) {
      if (this.total < this.limit) {
        return this.total - index;
      } else {
        return this.total - (this.page - 1) * this.limit - index;
      }
    },
    async getList() {
      this.loading = true;
      let res = await getHardwareKeFe(
        this.token,
        this.seller_id,
        this.formInline.user_name,
        this.formInline.telephone,
        "",
        // this.seller_names,
        this.page,
        this.limit
      );
      if (res.data.status) {
        this.tableData = res.data.data.data || [];
        this.total = res.data.data.total;
        // console.log(this.total, shouchu);
        let timer = setTimeout(() => {
          this.loading = false;
          clearTimeout(timer);
        }, 400);
      } else {
        if (res.data.msg == "token失效,请重新进行登录") {
          this.$router.push("/materilsLogin");
        }
        if (res.data.msg == "此账号没有权限") {
          this.$message.error(res.data.msg);
          this.loading = false;
        }
        let timer = setTimeout(() => {
          this.$message.error(res.data.msg);
        }, 5000);
      }
    },
    //编辑
    handleEdit(index, row) {
      if (row.status == 1) {
        this.$message.warning("启用时不能编辑");
        return;
      }
      this.dialogVisible = true;
      let obj = JSON.parse(JSON.stringify(row));
      this.form = obj;
      this.form.password = "";
      this.form.role_id = Number(obj.role_id);
      this.requirePassWord = "否";
      // let list = obj.limits_id.split(",");
      // for (let i = 0; i < list.length; i++) {
      //   list[i] = Number(list[i]);
      // }
      // console.log(list, 222);
      // this.form.limits_id = list;
      this.imageUrl = this.imgHeader + obj.avatar;
      this.imageUrl1 = obj.avatar;
    },
    //状态值
    conditionUser(id, status) {
      getHardwareKeFeStatus(this.token, id, status)
        .then((res) => {
          if (res.data.status) {
            this.$message.success(res.data.msg);
            this.getList();
          } else {
            if (res.data.msg == "token失效,请重新进行登录") {
              this.$router.push("/materilsLogin");
            }
            if (res.data.msg == "此账号没有权限") {
              this.$message.error(res.data.msg);
              this.loading = false;
            }
            let timer = setTimeout(() => {
              this.$message.error(res.data.msg);
            }, 1000);
          }
        })
        .catch((err) => {
          console.log(err.message);
        });
    },
    // 启用停用
    handleStatus(row) {
      if (row.status === 0) {
        let status = 1;
        this.conditionUser(row.id, status);
      } else {
        let status = 0;
        this.conditionUser(row.id, status);
      }
    },
    //删除
    // handleDelete(index, row) {
    //   console.log(index, row);
    // },
    //删除
    handleDelete(index, row) {
      this.$confirm("此操作将永久删除该客服, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log(row.id);
          delHardwareKeFe(this.token, row.id).then((res) => {
            if (res.data.status) {
              this.$message({
                type: "success",
                message: "删除成功",
              });
              this.getList();
            } else {
              this.$message.error(res.data.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //关闭
    handleClose(done) {
      this.clearData();
      this.$refs.form.resetFields();
      done();
    },
    //取消
    cancel() {
      this.clearData();
      this.$refs.form.resetFields();
      this.dialogVisible = false;
    },
    //确定
    //弹出框的确定按钮
    save() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            // 编辑
            editHardwareKeFe(
              this.token,
              2,
              this.seller_id,
              this.form.id,
              this.form.user_name,
              this.form.telephone,
              // this.form.seller_name,
              this.form.password,
              // this.form.job_number,
              this.form.role_id,
              this.imageUrl1
            ).then((res) => {
              if (res.data.status == true) {
                this.$message({
                  message: "修改成功",
                });
                this.dialogVisible = false;
                this.clearData();
                this.$refs.form.resetFields();
                this.getList();
              } else {
                this.$message.error(res.data.msg);
              }
            });
          } else {
            editHardwareKeFe(
              this.token,
              2,
              this.seller_id,
              "",
              this.form.user_name,
              this.form.telephone,
              // this.form.seller_name,
              this.form.password,
              // this.form.job_number,
              this.form.role_id,
              this.imageUrl1
            ).then((res) => {
              if (res.data.status) {
                this.$message({
                  message: "新增成功",
                });
                this.total = res.data.data.count;
                this.dialogVisible = false;
                this.clearData();
                this.$refs.form.resetFields();
                this.getList();
              } else {
                this.$message.error(res.data.msg);
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    // async confirm() {
    //   // console.log("this.form", ...this.form);
    //   let res = await editHardwareKeFe(
    //     this.token,
    //     this.seller_id,
    //     this.form.user_name,
    //     this.form.telephone,
    //     this.form.aeccount,
    //     this.form.password,
    //     this.form.avatar,
    //     this.form.seller_id,
    //     this.form.type,
    //     this.form.job_number,
    //   );
    //   if (res.data.status) {
    //     this.tableData = res.data.data.data || [];
    //     this.total = res.data.data.count;
    //     // console.log(this.total, shouchu);
    //     let timer = setTimeout(() => {
    //       this.loading = false;
    //       clearTimeout(timer);
    //     }, 400);
    //   } else {
    //     if (res.data.msg == "token失效,请重新进行登录") {
    //       this.$router.push("/materilsLogin");
    //     }
    //     if (res.data.msg == "此账号没有权限") {
    //       this.$message.error(res.data.msg);
    //       this.loading = false;
    //     }
    //     let timer = setTimeout(() => {
    //       this.$message.error(res.data.msg);
    //     }, 5000);
    //   }
    //   this.dialogVisible = false;
    // },
    //上传
    //超出文件个数的回调
    handleExceed() {
      this.$message({
        type: "warning",
        message: "超出最大上传文件数量的限制！",
      });
      return;
    },
    //这是我自定义的移除事件
    handleClosedelete(i) {
      this.fileList.splice(i, 1); //删除上传的文件
    },
    //上传文件的格式
    beforeUpload(file) {
      if (file.type != "" || file.type != null || file.type != undefined) {
        //截取文件的后缀，判断文件类型
        const FileExt = file.name.replace(/.+\./, "").toLowerCase();
        //计算文件的大小
        const isLt5M = file.size / 1024 / 1024 < 1; //这里做文件大小限制
        //如果大于50M
        if (!isLt5M) {
          this.$message.error("上传文件大小不能超过 1MB!");
          return false;
        }
        //如果文件类型不在允许上传的范围内
        if (this.fileType.includes(FileExt)) {
          return true;
        } else {
          this.$message.error("上传文件格式不正确!");
          return false;
        }
      }
    },
    fileChange(file, fileList) {
      this.fileList = fileList;
    },
    // 压缩文件
    compressFile() {
      let config = {
        quality: 0.5, //默认0.5  0-1
        // width:100,
        // height:100
      };
      this.fileList.forEach(async (item) => {
        // console.log("this.fileList1", this.fileList1);
        console.log("原图size1===>", item.size);
        let result = await compressImage({
          file: item.raw,
          config,
          fileName: item.name,
        });
        console.log("压缩后图片size1===>", result.finalFile.size);
        // this.imageList.push(result);
        this.srcList2 = result.finalFile;
        // console.log("aaa", result.finalFile);
        // console.log("bbb", this.srcList2);
        // console.log("this.srcList", this.srcList);
      });
      // console.log("压缩后图片1===>", this.imageList);
    },
    //上传文件的事件
    uploadFiles(item) {
      this.$message("文件上传中........");
      //上传文件的需要formdata类型;所以要转
      this.compressFile();
      let timer = setTimeout(() => {
        uploadFiles(this.srcList2).then((res) => {
          if (res.data.status != false || res.data.id != null) {
            res.data.data.saveurl; //半截
            res.data.data.weburl; //全拼
            this.imageUrl = res.data.data.weburl;
            this.imageUrl1 = res.data.data.saveurl;
            this.fileList.push(this.srcList2); //成功过后手动将文件添加到展示列表里
            let i = this.fileList.indexOf(this.srcList2);
            this.handleSuccess();
          }
        });
        clearTimeout(timer);
      }, 1000);
      // uploadFiles(item.file).then((res) => {
      //   if (res.data.status != false || res.data.id != null) {
      //     res.data.data.saveurl; //半截
      //     res.data.data.weburl; //全拼
      //     this.imageUrl = res.data.data.weburl;
      //     this.imageUrl1 = res.data.data.saveurl;
      //     this.fileList.push(item.file); //成功过后手动将文件添加到展示列表里
      //     let i = this.fileList.indexOf(item.file);
      //     this.handleSuccess();
      //   }
      // });
    },
    //上传成功后的回调
    handleSuccess() {
      this.$message({
        message: "上传成功",
        type: "success",
      });
      this.handleClosedelete();
    },
    //新增员工
    handleRemove() {},
    // 分页
    handleSizeChange(val) {
      this.limit = val;
      // console.log(`每页 ${val} 条`);
      this.getList();
    },
    // 第几页
    handleCurrentChange(val) {
      this.page = val;
      this.getList();
    },
  },
  created() {
    // this.currentPage;
    this.getList();
    this.getSelect();
    // this.getPrefixIdentIfication();
  },
};
</script>

<style scoped>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

.box-card {
  width: 100%;
}

.gauge {
  display: flex;
  margin: 0 20%;
}

.oneLine {
  display: flex;
  justify-content: space-between;
  margin-bottom: 14px;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.formUser {
  width: 60%;
}
.dialog-footer {
  display: flex;
  justify-content: center;
}
/* .fenlei {
  position: relative;
  height: 40px;
} */
/* .fenlei .fenlei2 {
  position: relative;
  left: 280px;
  top: -40px;
} */
</style>